package br.ufc.great.dtx.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import br.ufc.great.dtx.server.config.Config;

/**
 * 
 * @author Leonardo Oliveira Moreira
 *
 * Classe que implementa o servidor de requisi��es de clientes para o DTX
 */
public class DTXServer extends Thread {

	// ServerSocket que recebe as requisi��es dos clientes
	private ServerSocket serverSocket;
	// Stream de sa�da das informa��es do DTX
	private DTXOutput output;
	
	/**
	 * Construtor
	 * 
	 * @param output
	 */
	public DTXServer(DTXOutput output) {
		//setPriority(MAX_PRIORITY);
		try {
			this.output = output;
			serverSocket = new ServerSocket(Config.DTX_SERVER_PORT);
			output.print(getClass().getSimpleName(), "DTX is running", DTXOutput.HIGHLIGHT);
		}
		catch (NumberFormatException e) {
			output.print(e.getMessage(), DTXOutput.ERROR);
		}
		catch (IOException e) {
			output.print(e.getMessage(), DTXOutput.ERROR);
		}
	}
	
	/**
	 * Método de execu��o do servidor
	 */
	public void run() {
		while (isAlive() && serverSocket != null && ! serverSocket.isClosed()) {
			try {
				Socket socket = serverSocket.accept();
				DTXServerThread thread = new DTXServerThread(output, socket);
				thread.start();
			}
			catch (IOException e) {
				output.print(getClass().getSimpleName(), e.getMessage(), DTXOutput.ERROR);
			}
		}
	}
	
	/**
	 * Método utilizado para encerrar o servidor
	 */
	public void end() {
		try {
			if (serverSocket != null)
				serverSocket.close();
		}
		catch (IOException e) {

		}
		serverSocket = null;
		System.gc();
	}
	
}
